package com.aifast.system.log.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.aifast.common.base.R;
import com.aifast.common.layui.LayuiDataTable;
import com.aifast.common.layui.LayuiPageFactory;
import com.aifast.common.util.AiUtil;
import com.aifast.system.log.dao.LogLoginDao;
import com.aifast.system.log.entity.LogLogin;
import com.aifast.system.sys.entity.SysUser;
import com.aifast.system.sys.entity.UserInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 登录日志 服务实现类
 * </p>
 *
 * @author fujian
 * @since 2022-01-07
 */
@Service
public class LogLoginService extends ServiceImpl<LogLoginDao, LogLogin> {

    @Autowired
    private LogLoginDao dao;

    /**
     * layui数据表格列表查询方法
     * <br>这里参数不使用参数类，当超过5个参数时筛选条件参数建议使用参数类param封装
     * @param search 关键字搜索
     * @param page   分页
     * @return 列表数据
     */
    public LayuiDataTable list(String search, String startDate, String endDate, Page page) {
        LambdaQueryWrapper<LogLogin> wrapper = new LambdaQueryWrapper<LogLogin>()
                .like(StrUtil.isNotBlank(search), LogLogin::getRealName, search)
                .between((StrUtil.isNotBlank(startDate) && StrUtil.isNotBlank(endDate)),LogLogin::getCreateTime,startDate,endDate)
                .orderByDesc(LogLogin::getId);
        return LayuiPageFactory.init(page(page, wrapper));
    }

    /**
     * 新增或者查询
     * <br>vo的方法另写，里面有判定是否新增还是修改 可自定义逻辑
     *
     * @param logLogin
     * @return
     */
    public Boolean insertOrUpdate(LogLogin logLogin) {
        if (ObjectUtil.isNull(logLogin.getId())) {

        }
        return saveOrUpdate(logLogin);
    }

    /**
     * 删除方法
     * <br>提供单个删除和批量删除
     *
     * @param id  数据id
     * @param ids 数据id集合
     * @return
     */
    public Boolean del(Integer id, String ids) {
        List<Integer> integers = new ArrayList<>();
        if (StrUtil.isNotBlank(ids)) {
            integers = Convert.toList(Integer.class, ids.split(","));
        }
        if (ObjectUtil.isNotNull(id)) {
            integers.add(id);
        }
        try {
            integers.forEach(i -> {
                update(new UpdateWrapper<LogLogin>().set("deleted", 1).eq("id", i));
            });
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 数据详情
     *
     * @param id 数据id
     * @return
     */
    public R info(Integer id) {
        if (ObjectUtil.isNull(id)) return R.ERROR();
        LogLogin one = getOne(new QueryWrapper<LogLogin>().eq("id", id));
        return R.OK(one);
    }

    /**
     * 创建登录日志
     * @param one 用户数据类
     * @param request
     */
    public void putLog(SysUser one, HttpServletRequest request) {
        final UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        String ipAddr = AiUtil.getIpAddr(request);
        LogLogin build = LogLogin.builder()
                .userId(one.getId()).username(one.getUsername()).realName(one.getRealName()).createTime(LocalDateTime.now())
                .device(userAgent.getPlatform().toString()).browserType(userAgent.getBrowser().getName()).osName(userAgent.getOs().toString())
                .browserVersion(userAgent.getVersion()).type("login")
                .ip(ipAddr).ipAddress(AiUtil.getIpAddrHome(ipAddr))
                .build();
        insertOrUpdate(build);
    }

    public void putLogout(UserInfo one, HttpServletRequest request) {

        final UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        String ipAddr = AiUtil.getIpAddr(request);
        LogLogin build = LogLogin.builder()
                .userId(one.getUserId()).username(one.getUsername()).realName(one.getRealName()).createTime(LocalDateTime.now())
                .device(userAgent.getOs().getName()).browserType(userAgent.getBrowser().getName()).osName(userAgent.getOs().getName())
                .browserVersion(userAgent.getVersion()).type("logout")
                .ip(ipAddr).ipAddress(AiUtil.getIpAddrHome(ipAddr))
                .build();
        insertOrUpdate(build);

    }
}
